package com.bjc.nio.c5;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.bjc.nio.util.ByteBufferUtil.debugAll;

/**
 * @program: nettypro
 * @description: 文件异步非阻塞io
 * @author: bjc
 * @create: 2021-09-21 20:17
 */
@Slf4j
public class AioFileChannel {

    public static void main(String[] args) throws IOException {
        try {
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("D:\\iotest_delete\\file01.txt"), StandardOpenOption.READ);
            //参数1 byteBuffer
            //参数2 读取的起始位置
            //参数3 附件
            //参数4 回调对象 CompletionHandler
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin ...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                //read 成功
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed");
                    attachment.flip();
                    debugAll(attachment);
                }

                //read 失败
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end");
        }catch (IOException e){
            e.printStackTrace();
        }
        System.in.read();
    }
}
